{% extends 'base.html' %}

{% block title %}AI 智能词典{% endblock %}

{% block content %}
<div class="container mt-4">
    <!-- 搜索区域 -->
    <div class="row justify-content-center mb-4">
        <div class="col-md-8">
            <div class="search-container">
                <div class="input-group">
                    <input type="text" 
                           id="wordInput" 
                           class="form-control form-control-lg" 
                           placeholder="输入要查询的单词..."
                           autocomplete="off"
                           autofocus>
                    <button class="btn btn-primary btn-lg" onclick="lookupWord()">
                        <i class="fas fa-search"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 结果展示区域 -->
    <div class="row justify-content-center">
        <div class="col-md-8">
            <!-- 加载动画 -->
            <div id="loadingSpinner" class="text-center" style="display: none;">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
            </div>

            <!-- 单词详情卡片 -->
            <div id="resultCard" class="word-card" style="display: none;">
                <div class="word-header">
                    <h2 id="wordTitle" class="mb-0"></h2>
                    <div class="phonetic" id="phonetic"></div>
                </div>
                
                <div class="word-body">
                    <div class="definition-section">
                        <div class="pos-tag" id="posTag"></div>
                        <div class="definition" id="definition"></div>
                    </div>

                    <div class="examples-section mt-4">
                        <h5 class="section-title">
                            <i class="fas fa-quote-left"></i>
                            例句
                        </h5>
                        <div id="examples" class="examples-list"></div>
                    </div>
                </div>

                <!-- 难度信息 -->
                <div class="difficulty-section mt-4">
                    <h5 class="section-title">
                        <i class="fas fa-chart-bar"></i>
                        难度信息
                    </h5>
                    <div class="difficulty-info">
                        <div class="badge bg-primary">词频排名: <span id="frequencyRank"></span></div>
                        <div class="badge bg-info">难度等级: <span id="difficultyLevel"></span></div>
                        <div class="exam-categories" id="examCategories"></div>
                    </div>
                </div>
                
                <!-- 记忆助手 -->
                <div class="memory-section mt-4">
                    <h5 class="section-title">
                        <i class="fas fa-brain"></i>
                        记忆助手
                    </h5>
                    <div class="memory-tips">
                        <div class="tip-item">
                            <strong>词源:</strong> <span id="etymology"></span>
                        </div>
                        <div class="tip-item">
                            <strong>词根词缀:</strong> <span id="wordParts"></span>
                        </div>
                        <div class="tip-item">
                            <strong>联想记忆:</strong> <span id="association"></span>
                        </div>
                        <div class="tip-item">
                            <strong>记忆技巧:</strong> <span id="mnemonic"></span>
                        </div>
                    </div>
                </div>
                
                <!-- 词语辨析 -->
                <div class="comparison-section mt-4">
                    <h5 class="section-title">
                        <i class="fas fa-balance-scale"></i>
                        词语辨析
                    </h5>
                    <div id="comparisons" class="comparisons-list"></div>
                </div>
            </div>

            <!-- 错误提示 -->
            <div id="errorAlert" class="alert alert-danger" style="display: none;">
            </div>
        </div>
    </div>
</div>

<style>
/* 搜索框样式 */
.search-container {
    margin-bottom: 2rem;
}

.search-container .form-control {
    border-radius: 20px 0 0 20px;
    border: 2px solid var(--accent-color);
    padding: 0.75rem 1.5rem;
    font-size: 1.1rem;
    background-color: var(--dark-bg);
    color: var(--text-primary);
}

.search-container .btn {
    border-radius: 0 20px 20px 0;
    padding: 0.75rem 1.5rem;
    background-color: var(--accent-color);
    border-color: var(--accent-color);
}

/* 单词卡片样式 */
.word-card {
    background-color: var(--dark-secondary);
    border-radius: 15px;
    padding: 2rem;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    animation: fadeIn 0.3s ease-in-out;
}

.word-header {
    margin-bottom: 1.5rem;
    padding-bottom: 1rem;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.word-header h2 {
    color: var(--text-primary);
    font-size: 2.5rem;
    font-weight: 600;
}

.phonetic {
    color: var(--text-secondary);
    font-family: monospace;
    font-size: 1.2rem;
    margin-top: 0.5rem;
}

.pos-tag {
    display: inline-block;
    padding: 0.3rem 0.8rem;
    background-color: rgba(114, 137, 218, 0.2);
    color: var(--accent-color);
    border-radius: 12px;
    font-size: 0.9rem;
    margin-bottom: 0.8rem;
}

.definition {
    font-size: 1.2rem;
    color: var(--text-primary);
    line-height: 1.6;
}

.section-title {
    color: var(--text-primary);
    font-size: 1.2rem;
    margin-bottom: 1rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.examples-list {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.example-item {
    padding: 1rem;
    background-color: rgba(114, 137, 218, 0.1);
    border-radius: 10px;
    border-left: 4px solid var(--accent-color);
}

.example-item .english {
    color: var(--text-primary);
    font-size: 1.1rem;
    margin-bottom: 0.4rem;
}

.example-item .chinese {
    color: var(--text-secondary);
    font-size: 1rem;
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

/* 深色主题变量 */
:root {
    --dark-bg: #1a1a1a;
    --dark-secondary: #2d2d2d;
    --text-primary: #ffffff;
    --text-secondary: #a0a0a0;
    --accent-color: #7289da;
}

.english-container {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.btn-play {
    background: none;
    border: none;
    color: var(--accent-color);
    padding: 0.2rem 0.5rem;
    cursor: pointer;
    transition: all 0.2s ease;
}

.btn-play:hover {
    color: #5b6eae;
    transform: scale(1.1);
}

.btn-play.playing {
    animation: pulse 1s infinite;
}

@keyframes pulse {
    0% { opacity: 1; }
    50% { opacity: 0.5; }
    100% { opacity: 1; }
}

.difficulty-info {
    display: flex;
    gap: 1rem;
    margin-bottom: 1rem;
}

.badge {
    padding: 0.5rem 1rem;
    font-size: 0.9rem;
}

.memory-tips {
    background-color: var(--dark-secondary);
    padding: 1rem;
    border-radius: 8px;
}

.tip-item {
    margin-bottom: 0.8rem;
}

.tip-item strong {
    color: var(--accent-color);
}

.comparisons-list {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.comparison-item {
    background-color: var(--dark-secondary);
    padding: 1rem;
    border-radius: 8px;
    border-left: 4px solid var(--accent-color);
}

.comparison-item .word {
    font-size: 1.1rem;
    color: var(--accent-color);
    margin-bottom: 0.5rem;
}
</style>

<script>
// 添加回车键触发查询
document.getElementById('wordInput').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        lookupWord();
    }
});

async function lookupWord() {
    const word = document.getElementById('wordInput').value.trim();
    if (!word) return;
    
    document.getElementById('loadingSpinner').style.display = 'block';
    document.getElementById('resultCard').style.display = 'none';
    document.getElementById('errorAlert').style.display = 'none';
    
    try {
        const response = await fetch(`/prompts/dictionary/lookup/?word=${encodeURIComponent(word)}`);
        const data = await response.json();
        
        if (data.status === 'success') {
            displayResult(data.data);
        } else {
            showError(data.message || '查询失败，请重试');
        }
    } catch (error) {
        console.error('Error:', error);  // 添加错误日志
        showError('网络错误，请稍后重试');
    } finally {
        document.getElementById('loadingSpinner').style.display = 'none';
    }
}

function displayResult(data) {
    const resultCard = document.getElementById('resultCard');
    
    // 基本信息
    document.getElementById('wordTitle').textContent = data.word;
    document.getElementById('phonetic').textContent = data.phonetic;
    document.getElementById('posTag').textContent = data.pos;
    document.getElementById('definition').textContent = data.definition;
    
    // 例句
    const examplesHtml = data.examples.map(example => `
        <div class="example-item">
            <div class="english-container">
                <div class="english">${example.en}</div>
                <button class="btn btn-play" onclick="playAudio('${example.en.replace(/'/g, "\\'")}')">
                    <i class="fas fa-volume-up"></i>
                </button>
            </div>
            <div class="chinese">${example.cn}</div>
        </div>
    `).join('');
    document.getElementById('examples').innerHTML = examplesHtml;

    // 难度信息
    const difficultySection = document.querySelector('.difficulty-section');
    if (data.difficulty) {
        difficultySection.style.display = 'block';
        document.getElementById('frequencyRank').textContent = data.difficulty.frequency_rank;
        document.getElementById('difficultyLevel').textContent = data.difficulty.difficulty_level;
        const examHtml = data.difficulty.exam_categories
            .map(exam => `<span class="badge bg-secondary">${exam}</span>`)
            .join(' ');
        document.getElementById('examCategories').innerHTML = examHtml;
    } else {
        difficultySection.style.display = 'none';
    }

    // 记忆助手
    const memorySection = document.querySelector('.memory-section');
    if (data.memory_tips) {
        memorySection.style.display = 'block';
        document.getElementById('etymology').textContent = data.memory_tips.etymology;
        document.getElementById('wordParts').textContent = data.memory_tips.word_parts;
        document.getElementById('association').textContent = data.memory_tips.association;
        document.getElementById('mnemonic').textContent = data.memory_tips.mnemonic;
    } else {
        memorySection.style.display = 'none';
    }

    // 词语辨析
    const comparisonSection = document.querySelector('.comparison-section');
    if (data.comparisons && data.comparisons.length > 0) {
        comparisonSection.style.display = 'block';
        const comparisonsHtml = data.comparisons.map(comp => `
            <div class="comparison-item">
                <div class="word">${comp.word}</div>
                <div class="difference"><strong>词义差别:</strong> ${comp.difference}</div>
                <div class="usage"><strong>使用场合:</strong> ${comp.usage}</div>
                <div class="example"><strong>示例:</strong> ${comp.example}</div>
            </div>
        `).join('');
        document.getElementById('comparisons').innerHTML = comparisonsHtml;
    } else {
        comparisonSection.style.display = 'none';
    }

    // 显示结果卡片
    resultCard.style.display = 'block';
    resultCard.scrollIntoView({ behavior: 'smooth', block: 'start' });

    // 打印数据以便调试
    console.log('API Response:', data);
}

let currentAudio = null;

async function playAudio(text) {
    try {
        const button = event.currentTarget;
        const icon = button.querySelector('i');
        
        // 如果有正在播放的音频，停止它
        if (currentAudio) {
            currentAudio.pause();
            currentAudio = null;
            // 重置所有按钮的图标
            document.querySelectorAll('.btn-play i').forEach(i => {
                i.className = 'fas fa-volume-up';
            });
        }

        // 显示加载状态
        icon.className = 'fas fa-spinner fa-spin';
        
        // 获取音频数据
        const response = await fetch('/prompts/dictionary/speak/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({ text: text })
        });

        if (!response.ok) {
            throw new Error('语音生成失败');
        }

        const blob = await response.blob();
        const audioUrl = URL.createObjectURL(blob);
        
        // 创建并播放音频
        currentAudio = new Audio(audioUrl);
        
        // 播放开始时显示放状态
        currentAudio.onplay = () => {
            icon.className = 'fas fa-stop';
        };
        
        // 播放结束时重置状态
        currentAudio.onended = () => {
            URL.revokeObjectURL(audioUrl);
            currentAudio = null;
            icon.className = 'fas fa-volume-up';
        };
        
        // 错误处理
        currentAudio.onerror = () => {
            URL.revokeObjectURL(audioUrl);
            currentAudio = null;
            icon.className = 'fas fa-volume-up';
            showError('音频播放失败');
        };
        
        await currentAudio.play();

    } catch (error) {
        console.error('播放失败:', error);
        // 重置按钮状态
        const icon = event.currentTarget.querySelector('i');
        icon.className = 'fas fa-volume-up';
        showError('语音播放失败，请重试');
    }
}

// 显示错误提示
function showError(message) {
    const errorAlert = document.getElementById('errorAlert');
    errorAlert.textContent = message;
    errorAlert.style.display = 'block';
    
    // 3秒后自动隐藏错误提示
    setTimeout(() => {
        errorAlert.style.display = 'none';
    }, 3000);
}

// 获取 CSRF Token
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
</script>
{% endblock %} 